package com.sooncode.project.focusservice.service;

import com.alibaba.excel.EasyExcel;
import com.sooncode.project.core.finder.Finder;
import com.sooncode.project.core.finder.OType;
import com.sooncode.project.core.finder.Page;
import com.sooncode.project.core.finder.Sort;
import com.sooncode.project.core.model.DomainException;
import com.sooncode.project.focusservice.model.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CourseSettingService {

    public boolean add(Map map){
        CourseSetting courseSetting=new CourseSetting();
        courseSetting.add(map);
        asyncItemName(courseSetting.getId());
        return true;
    }
    public boolean modify(String id,Map map){
        CourseSetting courseSetting=getById(id);
        map.remove("createDate");
        courseSetting.modify(map);
        asyncItemName(courseSetting.getId());
        return true;
    }
    public boolean delete(String id){
        CourseSetting courseSetting=getById(id);
        courseSetting.delete();
        return true;
    }
    public Page<CourseSetting> getPageList(int pageSize, int pageIndex, Map map){
        return new Finder<>(CourseSetting.class).byMap(map).page(pageSize,pageIndex,Sort.DESC("createDate"));
    }
    public CourseSetting getById(String id){
        return new Finder<>(CourseSetting.class).byId(id);
    }

    public boolean copy(String id) {
        CourseSetting courseSetting=getById(id);
        courseSetting.copy();
        return true;
    }
    public List<CourseSetting> getCourseByLevel(String age, double level) {
        if(Integer.parseInt(age)<2) age="2";
        return new Finder<>(CourseSetting.class,false)
                .byField("age",age)
                .and("minScore",level, OType.lte)
                .and("maxScore",level, OType.gte)
                .list();
    }
    public boolean asyncItemName(String id){
        new Thread(() -> {
            List<Course> coursesList= new Finder<>(Course.class).list();
            int page=0;
            int pageSize=100;
            while(true) {
                Page<CourseSetting> pageList = new Finder<>(CourseSetting.class)
                        .byField("id", id).page(page, pageSize);
                for (CourseSetting setting : pageList.getContent()) {
                    for (CourseSettingItem item : setting.getItems()) {
                        List<String> names=new ArrayList<>();
                        for(String s:item.getCourses()){
                            coursesList.stream().filter(course -> course.getId().equals(s)).findFirst().ifPresent(course -> {
                                if(s.equals(course.getId())){
                                    names.add(course.getJoinName());
                                    item.setCourseNames(names);
                                }
                            });
                        }
                    }
                    setting.modify();
                }
                if(pageList.getContent().size()<pageSize){
                    break;
                }
                page++;
            }
        }).start();
        return true;
    }

    public Page<CourseSetting> getPageListForDevice(int pageSize, int pageIndex, Map map) {
        return new Finder<>(CourseSetting.class).byMap(map).page(pageSize,pageIndex,Sort.DESC("createDate"));
    }

    public void exportCourse(String testId, HttpServletResponse response) {
        Test test=new Finder<>(Test.class).byId(testId);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode(test.getName()+"的课程表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), CourseExcel.class).inMemory(true)
                    .sheet("课程表").doWrite(()->{
                        return new CourseExcel().export(test);
                    });
        }catch (Exception ex){
            ex.printStackTrace();
            throw new DomainException("导出文件时发生错误");
        }
    }
}
